package cn.twh.wall.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Random;

/**
 * 随机数工具
 *
 * @author TWH
 */
public class RandomUtil {
    protected static final Random RANDOM = new Random();

    /**
     * @param rate 最大100
     * @return 是否成功
     */
    public static boolean reteTrue(int rate) {
        if (rate > 100 || rate < 0) {
            throw new IllegalArgumentException("function need 0-100 rate,but arg is：" + rate);
        }
        return RANDOM.nextInt(100) <= rate;
    }

    /**
     * @param weight 权重 , 总和不能超过int.max且大于0
     * @return 对应下标
     */
    public static int weightIndex(int... weight) {
        int weightSum = 0;
        for (int weightValue : weight) {
            weightSum += weightValue;
        }
        int randomNum = RANDOM.nextInt(weightSum);
        double stepWeightSum = 0;
        for (int i = 0; i < weight.length; i++) {
            stepWeightSum += weight[i];
            if (randomNum < stepWeightSum) {
                return i;
            }
        }
        return -1;
    }

    public String genNumberLeftPad(int length) {
        String max = StringUtils.leftPad("", length, '9');
        int randomInt = RANDOM.nextInt(Integer.parseInt(max));
        return StringUtils.leftPad(String.valueOf(randomInt), length);
    }
}
